import Food from "./Food";
import ScorePanel from "./ScorePanel";
import Snake from "./Snake";


class GameControls {
    food:Food
    scorePanel:ScorePanel
    snake:Snake

    // 设置蛇的移动方向
    snakeDirection:string = ''

    // 判断蛇是否越界
    gameOver = true

    // 设置一个定时器
    timer = setTimeout(() => {}, 3000);

    constructor() {
        this.food = new Food()
        this.scorePanel = new ScorePanel(2,10)
        this.snake = new Snake()
        // this.snake.X = 20
        this.init()
    }



    // 游戏的初始化
    init() {
        // 注意this指向

        document.addEventListener('keydown',this.keyDownHandler.bind(this))
    }

    keyDownHandler(event:KeyboardEvent) {
        // console.log(event.code);
        
        this.snakeDirection = event.code
        this.snakeMove()
    }

    // 蛇行走方向
    snakeMove() {
        // 进来先清除定时器,否则按下右键之后，再按下左键会调用两个snakeMove函数，会有两个定时器
        clearTimeout(this.timer)
        
        let X = this.snake.X
        let Y = this.snake.Y

        switch (this.snakeDirection) {
            // 向下走 top + 1
            case 'ArrowDown':
            case 'Down':
                Y = Y + 10
                break;
            case 'ArrowUp':
            case 'Up':
                Y = Y - 10
                break;
            case 'ArrowLeft':
            case 'Left':
                X = X - 10
                break;
            case 'ArrowRight':
            case 'Right':
                X = X + 10 
                break;  
        }

        // 判断蛇头是否吃到食物
        this.eatFood(X,Y)

        // 先判断不能向反方向移动，然后移动身体

        // 移动身体   
        this.snake.bodies.length>1 && this.snake.moveBody()
        // 捕获错误
        try {
            this.snake.X = X
            this.snake.Y = Y
            
        } catch (error) {
            this.gameOver = false
            alert(error)
        }
        this.timer = setTimeout(this.snakeMove.bind(this), 300 - this.scorePanel.level *30)
        this.gameOver && this.timer;
    }

    // 判断蛇头是否吃到食物
    eatFood(X:number,Y:number) {
        if(X == this.food.X && Y == this.food.Y) {
            // 改变食物的地方
            this.food.change()
            // 修改分数
            this.scorePanel.addScore()
            // 吃到之后身体要+1
            this.snake.snakeElement.insertAdjacentHTML('beforeend','<div></div>')
            
        }

    }

}

export default GameControls